package com.starters.redisson.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * TODO: redisson自动装配
 *
 * @author wuyijie
 * @date 2022/2/13 12:15 AM
 */
@Configuration
@EnableConfigurationProperties(CustomizedRedissonProperties.class)
@ConditionalOnProperty(prefix = CustomizedRedissonProperties.PREFIX, name = "${MallRedissonProperties.enable}", havingValue = "true", matchIfMissing = true)
@Import(value = {
        RedissonDistributedLocker.class
})
public class CustomizedRedissonAutoConfiguration {
    private static final Logger LOGGER=Logger.getLogger(CustomizedRedissonAutoConfiguration.class.getName());

    @Value("${spring.redis.host}")
    private String redisHost;
    @Value("${spring.redis.port}")
    private String redisPort;
    @Value("${spring.redis.password}")
    private String redisPassword;

    public CustomizedRedissonAutoConfiguration() {
        LOGGER.info("<<  RedissonAutoConfiguration 构造方法已调用，构造完成  >>");
    }

    @Bean
    public RedissonClient redisson() throws IOException {
//        判断配置文件是否存在。如果存在使用配置文件的配置，否则使用默认的配置。
        File file = ResourceUtils.getFile("classpath:redisson-config.yml");
        if (file.exists()) {
            // 本例子使用的是yaml格式的配置文件，读取使用Config.fromYAML，如果是Json文件，则使用Config.fromJSON
            Config config = Config.fromYAML(CustomizedRedissonAutoConfiguration.class.getClassLoader().getResource("redisson-config.yml"));
            return Redisson.create(config);
        } else {
            // connects to 127.0.0.1:6379 by default
            Config config = new Config();
            config.useSingleServer().setAddress(redisHost + ":" + redisPort);
            config.useSingleServer().setPassword(redisPassword);
            return Redisson.create(config);
        }
    }
}
